package com.example.file_portal.controller;

import com.example.file_portal.bean.File;
import com.example.file_portal.service.FileService;
import com.example.file_portal.util.randomCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.List;

@Controller
public class HelloController {

    @GetMapping("/index")
    public String index(){

        return "index";
    }

    @Autowired
    FileService fileService;

    @ResponseBody
    @GetMapping("/code")
    public String getPassword(@RequestParam("code") String code){
        return fileService.getPassword(code);
    }

    @RequestMapping("/test")
    public String list(Model model) {
        List<File> list = fileService.findAllFiles();
        model.addAttribute("list", list);
        return "test";
    }

    @GetMapping("/upload")
    public String uploadPage(){
        return "upload";
    }

    //上传文件以及授予取件码
    @RequestMapping(value = "upload", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String upload(HttpServletRequest request, MultipartFile file, @RequestParam("password") String password) throws JSONException {
        //TODO:判断是否需要登录，判断文件大小
        //TODO:判断时间是否过期
        //TODO:二维码/直达链接下载
        //TODO:使用QQ用户注册
        System.out.println(password);
        System.out.println(request.getParameter("advance"));
        System.out.println(request.getParameter("times"));
        System.out.println(request.getParameter("days"));
        int days = 1;
        int times = 1;
        //password = request.getParameter("password");
        if (request.getParameter("advance").equals("true")) {
            days = Integer.parseInt(request.getParameter("days"));
            times = Integer.parseInt(request.getParameter("times"));
        }
        JSONObject json = new JSONObject();
        String path = request.getSession().getServletContext().getRealPath("/") + "\\file";
        Timestamp time1 = new Timestamp(System.currentTimeMillis());
        Timestamp time2 = new Timestamp(System.currentTimeMillis() + 86400000 * days);
        String code = randomCode.getRandomString();
        while (fileService.isExist(code)) {
            code = randomCode.getRandomString();
        }
        String fileName = code;
        json.put("code", code);
        java.io.File dir = new java.io.File(path, fileName);
        System.out.println(json);
        System.out.println(file.getOriginalFilename());


        //写入数据库操作
        try {
            file.transferTo(dir);
            System.out.println("the MD5 is " + com.example.file_portal.util.fileMD5.md5(dir));
            File fileInfo = new File();
            fileInfo.setFile(path);
            fileInfo.setCode(code);
            fileInfo.setUploadTime(time1);
            fileInfo.setDeltime(time2);
            fileInfo.setName(file.getOriginalFilename());
            fileInfo.setRemain(days);
            fileInfo.setPassword(com.example.file_portal.util.getMD5.getMD5(password));
            fileService.addFile(fileInfo);
            json.put("status", 0);
        } catch (IOException e) {
            e.printStackTrace();
            json.put("status", -1);
            return json.toString();
        }
        return json.toString();

    }

    public String saveFile(File fileinfo, MultipartFile file) {
        //TODO:前端不同的业务操作和文件的保存处理需要分离（暂时不需要）


        return "";
    }

    @GetMapping("/download")
    public String downloads(){
        return "download";
    }

    @RequestMapping(value = "download", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        String password = request.getParameter("password");
        password = com.example.file_portal.util.getMD5.getMD5(password);
        System.out.println(fileService.getPassword(code));
        if (fileService.isExist(code)) {
            if (fileService.getPassword(code) != null) {
                if (!fileService.getPassword(code).equals(password)) {
                    return "{\"Error\":\"-2\"}";//密码错误
                }
            }
            File file = fileService.findOneFile(code);
            fileService.getOnceFile(code);
            String name = file.getName();
            response.setCharacterEncoding("UTF-8");
            //设置ContentType字段值
            response.setContentType("text/html;charset=utf-8");
            response.addHeader("Content-type", "appllication/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "ISO8859-1"));
            //通知文件流读取文件
            InputStream in = request.getServletContext().getResourceAsStream("file/" + code);
            //获取response对象的输出流
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            //循环取出流中的数据
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }


        }
        return "{\"Error\":\"-1\"}";//文件不存在、取件码错误
    }

    @GetMapping("/success")
    public String successPage(){

        return "success";
    }

    @GetMapping("/showcode")
    public String showCodePage(){
        return "showcode";
    }

}
